from helpers import updateInfo
from helpers import Transactions
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Top earners page class """

    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
    
        # Sell stock selected
        if self.request.get('sells'):
            succ=Transactions.sellStock(user, self.request.get('sells'))
            if succ==0:
                self.response.out.write("Can not sell this stock (is it really yours?!)")
                

        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
    
        # The following two tables can be put in one single function
        # However, we plan to change their functionality so we leave it as is
         
        # Build top 10 (all times) earners table
        q_3 = db.GqlQuery("SELECT * FROM TrendUsers ORDER BY totalamount DESC")
        i=0
        table_users_Text="\ndata.addRows(%d);\n" % (q_3.count())
        for p in q_3:
                percentCng=round(float(p.totalamount/100),2)
                printPercentage, fontColor, changeSign= updateInfo.getPerInfo(percentCng)
                table_users_Text+="data.setCell(%d, 0, '%s', '<a href=/userProfile?q=%s>%s&nbsp</a>',{style: 'font-weight:bold;'});\n" % (i,p.tuser.nickname().capitalize(),p.tuser.email(),p.tuser.nickname().capitalize())
                table_users_Text+="data.setCell(%d, 1, %.2f, '%.2f');\n" % (i,p.totalamount,p.totalamount)
                table_users_Text+="data.setCell(%d, 2, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i,percentCng, changeSign, printPercentage, fontColor)
                if p.tuser!=user:
                    compareLink="<a href=\"#\" onClick=\"javascript:CompareUsers(\\'%s\\');\" class=\"sell\">Compare</a>" % p.tuser.email()
                else:
                    compareLink=""
                table_users_Text+="data.setCell(%d, 3, '%s');\n" % (i,compareLink)
                i=i+1
                
        # Build top 10 (last week) earners table
        q_3 = db.GqlQuery("SELECT * FROM TrendUsers ORDER BY lastweekprcnt DESC")
        i=0
        table_users_Text_week="\ndata2.addRows(%d);\n" % (q_3.count())
        for p in q_3:
                percentCng=p.lastweekprcnt
                printPercentage, fontColor, changeSign= updateInfo.getPerInfo(percentCng)
                table_users_Text_week+="data2.setCell(%d, 0, '%s', '<a href=/userProfile?q=%s>%s&nbsp</a>',{style: 'font-weight:bold;'});\n" % (i,p.tuser.nickname().capitalize(),p.tuser.email(),p.tuser.nickname().capitalize())
                table_users_Text_week+="data2.setCell(%d, 1, %.2f, '%.2f');\n" % (i,p.totalamount,p.totalamount)
                table_users_Text_week+="data2.setCell(%d, 2, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i,percentCng, changeSign, printPercentage, fontColor)
                if p.tuser!=user:
                    compareLink="<a href=\"#\" onClick=\"javascript:CompareUsers(\\'%s\\');\" class=\"sell\">Compare</a>" % p.tuser.email()
                else:
                    compareLink=""
                table_users_Text_week+="data2.setCell(%d, 3, '%s');\n" % (i,compareLink)
                i=i+1
    
        
        template_values = {
            'table_users_Text': table_users_Text,
            'table_users_Text_week': table_users_Text_week,
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'categoryName' : 'Top Earners',
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'top_head.html',
            'account_main_content' : 'top_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/top', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
